<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\SystemConfig;
use Qiniu\Auth;
use think\facade\Log;

class FileController extends BaseController
{
    /**
     * 获取七牛云上传Token
     */
    public function getQiniuUploadToken(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            // 获取七牛云配置
            $accessKey = SystemConfig::getConfig('storage_access_key');
            $secretKey = SystemConfig::getConfig('storage_secret_key');
            $bucket = SystemConfig::getConfig('storage_bucket');
            $domain = SystemConfig::getConfig('storage_domain');
            $region = SystemConfig::getConfig('storage_region', 'z0');  // 默认华东区域

            // 验证配置是否完整
            if (empty($accessKey) || empty($secretKey) || empty($bucket) || empty($domain)) {
                return json(['status' => 500, 'message' => '存储配置不完整']);
            }

            // 根据区域代码获取上传域名
            $uploadUrl = $this->getUploadUrl($region);
            if (!$uploadUrl) {
                return json(['status' => 500, 'message' => '无效的区域代码']);
            }

            // 初始化Auth对象
            $auth = new Auth($accessKey, $secretKey);

            // 生成上传策略
            $policy = [
                'deadline' => time() + 3600,
                'fsizeLimit' => 10 * 1024 * 1024,
                'mimeLimit' => 'image/jpeg;image/png;image/gif;application/pdf;application/msword;' .
                             'application/vnd.openxmlformats-officedocument.wordprocessingml.document;' .
                             'application/vnd.ms-excel;' .
                             'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'returnBody' => json_encode([
                    'key' => '$(key)',
                    'hash' => '$(etag)',
                    'size' => '$(fsize)',
                    'mimeType' => '$(mimeType)',
                    'width' => '$(imageInfo.width)',
                    'height' => '$(imageInfo.height)',
                    'url' => $domain . '/$(key)'
                ])
            ];

            // 生成上传Token
            $token = $auth->uploadToken($bucket, null, 3600, $policy);

            // 记录操作日志
            UserController::logOperation($user->id, 'get_upload_token', '获取文件上传Token', $request);

            return json([
                'status' => 200,
                'message' => '获取成功',
                'data' => [
                    'upload_token' => $token,
                    'domain' => $domain,
                    'upload_url' => $uploadUrl,  // 上传域名
                    'region' => $region,         // 区域代码
                    'expire_time' => date('Y-m-d H:i:s', time() + 3600),
                    'upload_config' => [
                        'max_size' => 10 * 1024 * 1024,
                        'allowed_types' => [
                            'image/jpeg',
                            'image/png',
                            'image/gif',
                            'application/pdf',
                            'application/msword',
                            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        ]
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取上传Token失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取上传Token失败：' . $e->getMessage()]);
        }
    }

    /**
     * 根据区域代码获取上传域名
     * @param string $region 区域代码
     * @return string|false 上传域名或false
     */
    private function getUploadUrl($region)
    {
        $regionMap = [
            'z0' => 'https://upload.qiniup.com',        // 华东区域
            'z1' => 'https://upload-z1.qiniup.com',     // 华北区域
            'z2' => 'https://upload-z2.qiniup.com',     // 华南区域
            'na0' => 'https://upload-na0.qiniup.com',   // 北美区域
            'as0' => 'https://upload-as0.qiniup.com',   // 东南亚区域
            'cn-east-2' => 'https://upload-cn-east-2.qiniup.com'  // 华东-浙江2区域
        ];

        return $regionMap[$region] ?? false;
    }

    /**
     * 验证文件大小和类型
     * @param int $size 文件大小（字节）
     * @param string $mimeType 文件类型
     * @return bool|string 验证通过返回true，否则返回错误信息
     */
    private function validateFile($size, $mimeType)
    {
        // 验证文件大小
        if ($size > 10 * 1024 * 1024) {
            return '文件大小不能超过10MB';
        }

        // 允许的文件类型
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];

        if (!in_array($mimeType, $allowedTypes)) {
            return '不支持的文件类型';
        }

        return true;
    }

    /**
     * 获取七牛云文件下载凭证
     * @param Request $request
     * @return \think\response\Json
     */
    public function getQiniuDownloadToken(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $fileKey = $request->param('file_key');
        if (empty($fileKey)) {
            return json(['status' => 400, 'message' => '文件标识不能为空']);
        }

        try {
            // 获取七牛云配置
            $accessKey = SystemConfig::getConfig('storage_access_key');
            $secretKey = SystemConfig::getConfig('storage_secret_key');
            $bucket = SystemConfig::getConfig('storage_bucket');
            $domain = SystemConfig::getConfig('storage_domain');

            // 验证配置是否完整
            if (empty($accessKey) || empty($secretKey) || empty($bucket) || empty($domain)) {
                return json(['status' => 500, 'message' => '存储配置不完整']);
            }

            // 初始化Auth对象
            $auth = new Auth($accessKey, $secretKey);

            // 私有空间访问链接
            $baseUrl = $domain . '/' . $fileKey;
            
            // 设置下载凭证有效期（3600秒）
            $deadline = time() + 3600;
            
            // 生成下载凭证
            $privateDownloadUrl = $auth->privateDownloadUrl($baseUrl, $deadline);

            // 记录操作日志
            UserController::logOperation(
                $user->id, 
                'get_download_token', 
                "获取文件下载凭证，文件：{$fileKey}", 
                $request
            );

            return json([
                'status' => 200,
                'message' => '获取成功',
                'data' => [
                    'download_url' => $privateDownloadUrl,
                    'file_key' => $fileKey,
                    'expire_time' => date('Y-m-d H:i:s', $deadline),
                    'file_info' => [
                        'base_url' => $baseUrl,
                        'domain' => $domain
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取下载凭证失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取下载凭证失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量获取文件下载凭证
     * @param Request $request
     * @return \think\response\Json
     */
    public function getQiniuBatchDownloadTokens(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $fileKeys = $request->param('file_keys');
        if (empty($fileKeys) || !is_array($fileKeys)) {
            return json(['status' => 400, 'message' => '文件标识列表不能为空']);
        }

        if (count($fileKeys) > 100) {
            return json(['status' => 400, 'message' => '单次请求文件数量不能超过100个']);
        }

        try {
            // 获取七牛云配置
            $accessKey = SystemConfig::getConfig('storage_access_key');
            $secretKey = SystemConfig::getConfig('storage_secret_key');
            $bucket = SystemConfig::getConfig('storage_bucket');
            $domain = SystemConfig::getConfig('storage_domain');

            // 验证配置是否完整
            if (empty($accessKey) || empty($secretKey) || empty($bucket) || empty($domain)) {
                return json(['status' => 500, 'message' => '存储配置不完整']);
            }

            // 初始化Auth对象
            $auth = new Auth($accessKey, $secretKey);

            // 设置下载凭证有效期（3600秒）
            $deadline = time() + 3600;

            $results = [];
            foreach ($fileKeys as $fileKey) {
                $baseUrl = $domain . '/' . $fileKey;
                $privateDownloadUrl = $auth->privateDownloadUrl($baseUrl, $deadline);
                
                $results[] = [
                    'file_key' => $fileKey,
                    'download_url' => $privateDownloadUrl,
                    'base_url' => $baseUrl
                ];
            }

            // 记录操作日志
            UserController::logOperation(
                $user->id, 
                'get_batch_download_tokens', 
                "批量获取文件下载凭证，文件数量：" . count($fileKeys), 
                $request
            );

            return json([
                'status' => 200,
                'message' => '获取成功',
                'data' => [
                    'files' => $results,
                    'expire_time' => date('Y-m-d H:i:s', $deadline),
                    'domain' => $domain
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('批量获取下载凭证失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '批量获取下载凭证失败：' . $e->getMessage()]);
        }
    }
} 